const {
  CurrencyShopModel
} = require('../../../utils/currencyshop-model.js')
const {
  MemberModel
} = require('../../../utils/member-model.js')
const memberModel = new MemberModel()
const currencyShopModel = new CurrencyShopModel()
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopName: '',
    shopId: '',
    currency: {},
    number: '1',
    productMoney: '0.00',
    totalMoney: {
      price: 0,
      int: '0',
      float: '00'
    },
    currencyPrice: {
      int: '0',
      float: '00'
    },
    orderInfo: {},
    gifts: [],
    couponNum: 0,
    selectCoupon: '',
    couponPrice: '0.00',
    couponDiscount: '',
    fullDiscount: '',
    fullDiscountPrice: '',
    fullReduction: '',
    authShow: false,
    selectCouponType: false,
    numShow: false,
    shopAddress: '', //门店地址
    revenueCode: '',
    revenueName: "", //商品名称
    busType: '',
    operatorId: '',
    operatorName: '',
    merchantId: '',
    productImg: '',
    memberId: '', //会员id
  },

  decrease() {
    const number = +this.data.number
    this.setData({
      selectCoupon: ''
    })
    if (number > 1) {
      this.setData({
        number: number - 1 + ''
      })
      this.getOrderInfo()
    }
  },
  increase() {
    const number = +this.data.number
    this.setData({
      selectCoupon: ''
    })
    if (number < 999) {
      this.setData({
        number: number + 1 + ''
      })
      this.getOrderInfo()
    }
  },
  inputNum(event) {
    this.setData({
      selectCoupon: ''
    })
    if (event.detail.value === '' || event.detail.value === '0') {
      wx.showToast({
        title: '请填写正确数量',
        icon: 'none'
      })
      this.setData({
        number: '1'
      })
    } else {
      this.setData({
        number: event.detail.value
      })
    }
    this.getOrderInfo()
  },
  /**
   * 移动收银台扫码item参数
   */
  formatItem() {
    const currency = this.data.currency
    return {
      packageFlag: currency.packageFlag,
      packageId: currency.packageId,
      productSku: currency.productSku,
      itemQty: +this.data.number,
      price: currency.price || '',
    }
  },

  goSelectCoupon() {
    if (this.data.couponNum) {
      wx.reportAnalytics('currency_coupon')
      const item = this.formatItem()
      const selectCoupon = this.data.selectCoupon
      const assetId = selectCoupon ? selectCoupon.assetId : ''
      wx.navigateTo({
        url: `/pages/currencyShop/selectCoupon/index?shopId=${this.data.shopId}&items=${JSON.stringify(item)}&assetId=${assetId}&orderType=mobile&operatorId=${this.data.operatorId}&operatorName=${this.data.operatorName}&busType=${this.data.busType}`,
      })
    }
  },
  formSubmit(e) {
    if (app.globalData.isLogin) {
      wx.reportAnalytics('currency_pay')
      memberModel.userMessage({
        merchantId: wx.getStorageSync('merchantId'),
        formIds: [e.detail.formId]
      }).then(() => {
        this.wechatPay()
      }).catch(() => {
        this.wechatPay()
      })
    } else {
      this.setData({
        authShow: true
      })
    }
  },
  wechatPay() {
    const item = this.formatItem()
    let params = {
      merchantId: this.data.merchantId,
      items: [item],
      shopId: this.data.shopId,
      payPlatform: 'WECHAT_MALL',
      orderType: 'GAME_CURRENCY',
      busType: this.data.busType,
      operatorId: this.data.operatorId,
      operatorName: this.data.operatorName,
      revenueCode: this.data.revenueCode,
      amount: this.data.productMoney
    }
    const selectCoupon = this.data.selectCoupon
    if (selectCoupon) {
      params.couponCode = selectCoupon.couponId
      params.couponAssetId = selectCoupon.assetId
      params.couponMemberId = this.data.memberId
    }
    // 创建订单
    let requestOrder = currencyShopModel.mobileCreateOrder(params)
    return new Promise((resolve, reject) => {
      requestOrder.then(({
        orderCode,
        orderPaySummaryList
      }) => {
        if (orderPaySummaryList[0].amountPayable == 0 && orderPaySummaryList[0].priceType == 0) {
          var that = this;
          wx.reportAnalytics('currency_pay_succ')
          that.setData({
            selectCoupon: ''
          }, function () {
            wx.navigateTo({
              url: `/pages/currencyShop/buyComplete/index?orderCode=${orderCode}&shopId=${that.data.shopId}`
            })
          })
        } else {
          // 创建支付订单
          currencyShopModel.createPayOrder({
            merchantId: this.data.merchantId,
            shopId: this.data.shopId,
            orderCode,
            channel: 'WEIXIN',
            payMethod: 'WAP_PAY'
          }).then(({
            payInfo
          }) => {
            wx.requestPayment({
              timeStamp: payInfo.timeStamp,
              nonceStr: payInfo.nonceStr,
              package: payInfo.package,
              signType: payInfo.signType,
              paySign: payInfo.paySign,
              success: () => {
                var that = this;
                wx.reportAnalytics('currency_pay_succ')
                that.setData({
                  selectCoupon: ''
                }, function () {
                  wx.navigateTo({
                    url: `/pages/currencyShop/buyComplete/index?orderCode=${orderCode}&shopId=${that.data.shopId}`
                  })
                })
              },
              fail: () => {
                wx.reportAnalytics('currency_pay_fail')
              }
            })
          }).catch(err => {
            wx.reportAnalytics('currency_pay_fail')
            wx.showToast({
              title: `${err.error}`,
              icon: 'none'
            })
          })
        }
      }).catch(err => {
        wx.reportAnalytics('currency_pay_fail')
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
      })
    })
  },


  getOrderInfo() {
    const item = this.formatItem()
    let params = {
      merchantId: this.data.merchantId,
      shopId: this.data.shopId,
      busType: this.data.busType,
      operatorId: this.data.operatorId,
      operatorName: this.data.operatorName,
      items: [item],
      // payPlatform: 'BOSS_ORDER'
    }
    const selectCoupon = this.data.selectCoupon
    if (selectCoupon) {
      params.couponCode = selectCoupon.couponId
      params.couponAssetId = selectCoupon.assetId
      params.couponMemberId = this.data.memberId
      this.getCouponOrder(params)
    } else {
      if (app.globalData.isLogin && !this.data.selectCouponType) {
        this.getCoupon(params);
      } else {
        this.getCouponOrder(params)
      }
    }

  },

  getCoupon(paramsdata) {
    let param = paramsdata;
    const item = this.formatItem()
    return new Promise((resolve, reject) => {
      currencyShopModel.getMobileCouponList({
        merchantId: this.data.merchantId,
        shopId: this.data.shopId,
        items: [item],
        busType: this.data.busType,
        operatorId: this.data.operatorId,
        operatorName: this.data.operatorName,
      }).then(data => {
        data = data || []
        this.setData({
          couponNum: data.length,
          // 进页面自动选择优惠券
          // selectCoupon: this.data.selectCoupon ? this.data.selectCoupon : (data[0] || '')
        }, function () {
          const selectCoupon = this.data.selectCoupon
          if (selectCoupon) {
            param.couponCode = selectCoupon.couponId
            param.couponAssetId = selectCoupon.assetId
            param.couponMemberId = this.data.memberId
            this.getCouponOrder(param)
          } else {
            this.getCouponOrder(param)
          }
        })
        resolve(data)
      }).catch(err => {
        this.getCouponOrder(param)
        reject(err)
      })
    })
  },


  getCouponOrder(params) {
    let request = null
    request = currencyShopModel.mobilePriceQuery(params)
    return new Promise((resolve, reject) => {
      request.then(data => {
        const orderInfo = data || {}
        this.setData({
          orderInfo,
          gifts: orderInfo.gifts || []
        })

        const payPrice = orderInfo.finalOrderPrice || 0
        const split = payPrice.toFixed(2).split('.')
        this.setData({
          productMoney: (orderInfo.originalPrice || 0).toFixed(2),
          totalMoney: {
            price: payPrice,
            int: split[0],
            float: split[1]
          },
          couponPrice: (orderInfo.couponPrice || 0).toFixed(2),
          couponDiscount: orderInfo.couponDiscount ? orderInfo.couponDiscount || 0 : '',
          fullDiscount: orderInfo.fullDiscount,
          fullDiscountPrice: orderInfo.fullDiscountPrice ? (orderInfo.fullDiscountPrice || 0).toFixed(2) : '',
          fullReduction: orderInfo.fullReduction ? (orderInfo.fullReduction || 0).toFixed(2) : ''
        })
        resolve(orderInfo)
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none'
        })
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserInfo();
    const itemData = JSON.parse(decodeURIComponent(options.itemParam)) || ''
    const packagePrice = parseFloat(itemData.items[0].price) || 0
    const split = packagePrice.toFixed(2).split('.')
    this.setData({
      merchantId: itemData.merchantId || "",
      productImg: itemData.imgUrl || "",
      revenueName: itemData.revenueName || "",
      revenueCode: itemData.revenueCode || "",
      busType: itemData.busType || "",
      operatorId: itemData.operatorId || "",
      operatorName: itemData.operatorName || "",
      shopName: itemData.shopName || "",
      shopId: itemData.shopId || "",
      shopAddress: itemData.shopAddress || "",
      currency: itemData.items[0] || "{}",
      currencyPrice: {
        int: split[0],
        float: split[1]
      },
    }, () => {
      if (this.data.busType != "CASH_ITEM_RECEIVED") {
        this.getOrderInfo()
        currencyShopModel.getConfig({
          merchantId: this.data.merchantId,
          shopId: this.data.shopId,
          dictKeys: 'viewProductSwitch'
        }).then(data => {
          if (data.viewProductSwitch == '1') {
            this.setData({
              numShow: true
            })
          }
        })
      } else {
        this.setData({
          productMoney: packagePrice.toFixed(2),
          totalMoney: {
            price: packagePrice,
            int: split[0],
            float: split[1]
          },
        })
      }
    })
  },
  /**
   *微信会员信息
   */
  getUserInfo: function () {
    var that = this;
    memberModel.userInfo({
      merchantId: wx.getStorageSync('merchantId')
    }).then(data => {
      that.setData({
        memberId: data.memberId,
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})